package zju.ccnt.rest.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import zju.ccnt.rest.api.ApiEndUser;
import zju.ccnt.rest.service.EndUserServiceImpl;
import zju.ccnt.oauth2.Role;
import zju.ccnt.oauth2.user.api.ChangePasswordRequest;
import zju.ccnt.oauth2.user.api.CreateUserRequest;
import zju.ccnt.oauth2.user.api.CreateUserResponse;

/**
 * Created by zha on 14/11/6.
 */
@RequestMapping(value = "/end_user")
@RestController
public class EndUserController {

    private EndUserServiceImpl endUserService;

    private static final String ASK_ACCESS_TOKEN_CALL_BACK_URI = "/oauth/token";

    @Autowired
    public EndUserController(final EndUserServiceImpl endUserService) {
        this.endUserService = endUserService;
    }

    /**
     * Create a new end user
     * Return :
     *     ApiEndUser : contains basic info
     *     callbackUrI: uri after register to get the access_token
     */
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<CreateUserResponse> createEndUser(@RequestBody CreateUserRequest<ApiEndUser> createUserRequest){
        ApiEndUser apiEndUser = endUserService.createUser(createUserRequest, Role.USER);
        return new ResponseEntity<CreateUserResponse>(
                new CreateUserResponse<ApiEndUser>(apiEndUser, ASK_ACCESS_TOKEN_CALL_BACK_URI),
                HttpStatus.OK
        );
    }

    /**
     * change the password
     * @param changePasswordRequest
     * @param authentication
     * @return
     */
    @RequestMapping(value = "/password", method = RequestMethod.POST)
    @PreAuthorize(value="hasRole('USER')")
    public ResponseEntity<String> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest,Authentication authentication) {
        endUserService.updateUserPassword(changePasswordRequest, authentication);

        return new ResponseEntity<String>(ASK_ACCESS_TOKEN_CALL_BACK_URI, HttpStatus.OK);
    }

}
